import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getSongDownloadAPI, getSongLyricAPI, getplayAPI, getplayGrayAPI } from "../api";
import { RootState } from "@/store";
import ParseLyric from "@/utils/parse-lyric";
// import match from "@unblockneteasemusic/server";
// global.hosts = { 'i.y.qq.com': '10.63.85.137' };

// 获取播放歌曲的地址
export const feachSongUrlAction = createAsyncThunk<void, number>("songUrl", async (id, { dispatch }) => {
  const res = await getplayGrayAPI(id)

  // 可以做为一个设置 是否为 url来匹配
  if (res.data.url) {
    dispatch(changeSongUrlAction(res.data.url))
  } else {
    const { data } = await getplayAPI(id)
    dispatch(changeSongUrlAction(data[0].url))
  }
})

// 获取歌曲详情/ 歌曲播放 /歌曲列表
export const changeSongdetailAction = createAsyncThunk<void, number, { state: RootState }>("songdetail", async (id, { dispatch, getState }) => {
  const state = getState()
  const songList = state.player.songList
  const finIndex = state.player.songList.findIndex(item => item.id === id)

  if (finIndex === -1) {
    dispatch(feachSongUrlAction(id))
    const { songs } = await getSongDownloadAPI(id)
    dispatch(changeSongInfoAction(songs[0]))
    dispatch(changeSongListAction(songs[0]))
    dispatch(changeSongCurrIndexAction(songList.length))
  } else {
    const songs = songList[finIndex]
    dispatch(changeSongInfoAction(songs))
  }

  const { lrc } = await getSongLyricAPI(id)
  dispatch(changeSongLyricAction(ParseLyric(lrc.lyric)))
})

// 切换歌曲/模式的变化
export const changeMusicAction = createAsyncThunk<void, boolean, { state: RootState }>("changeMusic", async (next, { dispatch, getState }) => {
  const state = getState()
  const playList = state.player.songList
  const currSongIndex = state.player.currIndex
  const moduType = state.player.modeType
  let newIndex = currSongIndex

  if (moduType === 1) {
    // 随机播放
    newIndex = Math.floor(Math.random() * playList.length)
  } else {
    newIndex = next ? newIndex + 1 : newIndex - 1
    if (newIndex >= playList.length) newIndex = 0
    if (newIndex < 0) newIndex = playList.length - 1
  }
  // 获取当前的播放的歌曲
  const songs = playList[newIndex]
  dispatch(feachSongUrlAction(songs.id))
  dispatch(changeSongInfoAction(songs))
  dispatch(changeSongCurrIndexAction(newIndex))

  // 保存格式化的歌词
  const { lrc } = await getSongLyricAPI(songs.id)
  dispatch(changeSongLyricAction(ParseLyric(lrc.lyric)))
})

// 添加到播放列表
export const AddPlaySongListAction = createAsyncThunk<void, any, { state: RootState }>("playSonglist", (song, { dispatch, getState }) => {
  const state = getState()
  const songList = state.player.songList
  // 进行逻辑判断 查看歌曲列表中是否有该歌曲
  const finalIndex = songList.findIndex(item => item.id === song.id)
  if (finalIndex === -1) {
    // 添加到我们的歌曲列表
    dispatch(changeSongListAction(song))
  } else {
    return
  }
})

export
  interface IState {
  playSongInfo: any,
  songUrl: string,
  currIndex: number,
  songList: any[]
  modeType: number,
  lyric: any[]
}

const initialState: IState = {
  playSongInfo: {
    "name": "我们的时光",
    "id": 29567193,
    "pst": 0,
    "t": 0,
    "ar": [
      {
        "id": 6731,
        "name": "赵雷",
        "tns": [],
        "alias": []
      }
    ],
    "alia": [],
    "pop": 100,
    "st": 0,
    "rt": null,
    "fee": 8,
    "v": 49,
    "crbt": null,
    "cf": "",
    "al": {
      "id": 3048030,
      "name": "吉姆餐厅",
      "picUrl": "https://p1.music.126.net/PJNV84mjt_mDXEkxtjzB4w==/18957779486268444.jpg",
      "tns": [],
      "pic_str": "18957779486268444",
      "pic": 18957779486268444
    },
    "dt": 270746,
    "h": {
      "br": 320000,
      "fid": 0,
      "size": 10832501,
      "vd": -45877,
      "sr": 44100
    },
    "m": {
      "br": 192000,
      "fid": 0,
      "size": 6499518,
      "vd": -43262,
      "sr": 44100
    },
    "l": {
      "br": 128000,
      "fid": 0,
      "size": 4333026,
      "vd": -41509,
      "sr": 44100
    },
    "sq": {
      "br": 841498,
      "fid": 0,
      "size": 28479102,
      "vd": -45864,
      "sr": 44100
    },
    "hr": null,
    "a": null,
    "cd": "1",
    "no": 4,
    "rtUrl": null,
    "ftype": 0,
    "rtUrls": [],
    "djId": 0,
    "copyright": 2,
    "s_id": 0,
    "mark": 8192,
    "originCoverType": 1,
    "originSongSimpleData": null,
    "tagPicList": null,
    "resourceState": true,
    "version": 49,
    "songJumpInfo": null,
    "entertainmentTags": null,
    "awardTags": null,
    "single": 0,
    "noCopyrightRcmd": null,
    "mst": 9,
    "cp": 1400821,
    "rtype": 0,
    "rurl": null,
    "mv": 366072,
    "publishTime": 1413648000007
  },
  songUrl: "",
  songList: [
    {
      "name": "水星记",
      "id": 441491828,
      "pst": 0,
      "t": 0,
      "ar": [
        {
          "id": 2843,
          "name": "郭顶",
          "tns": [],
          "alias": []
        }
      ],
      "alia": [],
      "pop": 100,
      "st": 0,
      "rt": null,
      "fee": 8,
      "v": 56,
      "crbt": null,
      "cf": "",
      "al": {
        "id": 35005583,
        "name": "飞行器的执行周期",
        "picUrl": "https://p1.music.126.net/wSMfGvFzOAYRU_yVIfquAA==/2946691248081599.jpg",
        "tns": [],
        "pic": 2946691248081599
      },
      "dt": 325266,
      "h": {
        "br": 320000,
        "fid": 0,
        "size": 13013203,
        "vd": -29142,
        "sr": 44100
      },
      "m": {
        "br": 192000,
        "fid": 0,
        "size": 7807939,
        "vd": -26509,
        "sr": 44100
      },
      "l": {
        "br": 128000,
        "fid": 0,
        "size": 5205307,
        "vd": -24735,
        "sr": 44100
      },
      "sq": {
        "br": 727754,
        "fid": 0,
        "size": 29589266,
        "vd": -29902,
        "sr": 44100
      },
      "hr": null,
      "a": null,
      "cd": "1",
      "no": 5,
      "rtUrl": null,
      "ftype": 0,
      "rtUrls": [],
      "djId": 0,
      "copyright": 1,
      "s_id": 0,
      "mark": 8192,
      "originCoverType": 1,
      "originSongSimpleData": null,
      "tagPicList": null,
      "resourceState": true,
      "version": 56,
      "songJumpInfo": null,
      "entertainmentTags": null,
      "awardTags": null,
      "single": 0,
      "noCopyrightRcmd": null,
      "rtype": 0,
      "rurl": null,
      "mst": 9,
      "cp": 7003,
      "mv": 5404031,
      "publishTime": 1480003200000
    }
  ],
  currIndex: 0, // 播放列表 当前播放到哪一首歌曲了
  modeType: 0, // 歌曲的播放模式 0顺序 1随机 2单曲循环
  lyric: []
}

const playerSlice = createSlice({
  name: 'player',
  initialState,
  reducers: {
    changeSongUrlAction(state, { payload }) {
      state.songUrl = payload
    },
    changeSongInfoAction(state, { payload }) {
      state.playSongInfo = payload
    },
    changeSongListAction(state, { payload }) {
      state.songList.push(payload)
    },
    changeSongCurrIndexAction(state, { payload }) {
      state.currIndex = payload
    },
    changeSongModeTypeAction(state) {
      let newModeType = state.modeType
      newModeType = newModeType + 1
      if (newModeType > 2) newModeType = 0
      if (newModeType < 0) newModeType = 2
      state.modeType = newModeType
    },
    changeSongLyricAction(state, { payload }) {
      state.lyric = payload
    }
  }
})

export const { changeSongUrlAction, changeSongInfoAction, changeSongListAction,
  changeSongCurrIndexAction, changeSongModeTypeAction, changeSongLyricAction } = playerSlice.actions
export default playerSlice.reducer